from base.views import TemplateView, ActionView

from flask import Blueprint, redirect, url_for, request
from flask_login import login_required, logout_user, login_user

from models import User, Tab, Tag
from utils import get_param
from flask import jsonify

manage = Blueprint('manage', __name__, url_prefix='/manage')


class TabView(TemplateView):
    template_name = 'manage/tabs.html'

    def get_context_data(self):
        context = super().get_context_data()
        context['tabs'] = Tab.all()
        return context

    def post(self):
        if request.is_xhr:
            data = {}

            type = get_param('type', 'string', required=True,
                max_length=64, min_length=1)
            if type == "tab":
                name = get_param('name', 'string', required=True,
                    max_length=64, min_length=1)
                tab = Tab.create(name)
                if tab:
                    return jsonify({
                        'ret': 20000,
                        'redirect': '/manage/tabs'
                    })
                else:
                    return jsonify({
                        'ret': 30000,
                        'msg': '创建失败'
                    })
            else:
                name = get_param('name', 'string', required=True,
                    max_length=64, min_length=1)
                tab_id = get_param('tab_id', 'string', required=True)
                tag = Tag.create(name, tab_id)
                if tag:
                    return jsonify({
                        'ret': 20000,
                        'redirect': '/manage/tabs'
                    })
                else:
                    return jsonify({
                        'ret': 30000,
                        'msg': '创建失败'
                    })
        return self.get()


def register():
    manage.add_url_rule('/', view_func=TabView.as_view('index'))
    manage.add_url_rule('/tabs', view_func=TabView.as_view('tabs'))